<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Admin extends CI_Controller {

	function __construct() {

		// Need to run CI_Controller constructor
		parent::__construct();

		// Load the user model
		// This is needed for checking user is logged in and has permission to access the page
		$this->load->model('user');
	}

	/**
	 * Welcome page for admin panel
	 */
	public function index() {

		// Check if the user is logged in and has permission to view page
		if ( ! $this->user->is_logged()  ) { redirect('welcome/login'); }
		if ( ! $this->user->is_administrator() ) { redirect('welcome'); }

		// Page title to send to view
		$data['page_title'] = "Administration";
		// Page content 
		$data['main_content'] = "admin/admin_home";

		// Template Settings
		$data['content_title'] = 'Adminsitration Homepage';
		$data['left_sidebar'] = 'admin_links';
		$data['sidebar_modifier'] = 'Hide Right';
		$data['left_sidebar_title'] = 'Administration';

		// Load the welcome page for the admin section
		$this->load->view('template', $data);
	}

	public function manage_users() {

		// Check if the user is logged in and has permission to view page
		if ( ! $this->user->is_logged()  ) { redirect('welcome/login'); }
		if ( $this->user->is_student() ) { redirect('welcome/login'); }

		$this->load->model('settings');

		// Check if the add user form has been submitted
		if ( $this->input->post('qut_id') ) {

			$data = $this->input->post();

			//TODO: Validate user info
						
			// Load the add user function from the user model
			$result = $this->user->add_user($data, false, $this->settings->get_setting('email_passwords'));
			
			redirect('admin/manage_users');

		}

		// Check if the user is aploading a csv
		if ( $this->input->post('upload') ) {
			// If a csv file has been uploaded
			
			$config['upload_path'] = './uploads/';
			$config['allowed_types'] = 'csv|text/comma-separated-values|application/csv|application/excel|application/vnd.ms-excel|application/vnd.msexcel|text/anytext|text/plain|text/csv';
			$config['file_name'] = time() . '_' . uniqid() . '.csv';
			$config['max_size']	= '1000';

			$this->load->library('upload', $config);

			if ( $this->upload->do_upload() ) {
				// File data
				$upload_data = array( 'upload_data' => $this->upload->data() );
				$upload_data = $upload_data['upload_data'];

				$import_config['file_path'] = base_url() . 'uploads/' . $upload_data['file_name'];
				$import_config['named_fields'] = TRUE;
				$import_config['separator'] = ',';
				$import_config['enclosure'] = '"';

				// If any users cannot be imported an error will be displayed
				// // TODO: Allow skipping failed user add
				if ( $this->user->import_users($import_config, $this->input->post('role'), $this->settings->get_setting('email_passwords') ) ) {
					$this->session->set_flashdata('notices', 'Users imported successfully.' );
				} else {
					$this->session->set_flashdata('errors', 'An error occured while importing a user.' );
				}
				redirect('admin/manage_users');
			} else {
				// Set the error message
				$this->session->set_flashdata('errors', 'Error: Cannot Upload CSV File.' );
				redirect('admin/manage_users');
			}

		}

		// Check if the user is changing a students class
		if ( $this->input->post('change_class') ) {
			// Get the post data
			$data = $this->input->post();
			// Run the user update function
			if ( $this->user->change_class($data['user_id'], $data['class_id']) ) {
				$this->session->set_flashdata('notices', 'Class has been changed successfully' );
			} else {
				$this->session->set_flashdata('errors', 'Error: Class could not be changed.' );
			}
			redirect('admin/manage_users');
		}

		// Check if the user wants to delete a user
		if ( $this->uri->segment(3) === 'delete' ) {
			if ( $this->uri->segment(4) ) {
				$this->user->remove_user( $this->uri->segment(4) );
				$this->session->set_flashdata('notices', 'User removed successfully.' );
			} else {
				$this->session->set_flashdata('errors', 'Cannot delete user: No user ID specified' );
			}
			redirect('admin/manage_users');
		}

		// Load the class model so we can get a list of all classes
		$this->load->model('classes');

		$data['user_data'] = $this->user->get_user_data();
		$data['class_data'] = $this->classes->get_class_data();

		// Page title to send to view
		$data['page_title'] = "Administration";
		// Page content 
		$data['main_content'] = "admin/manage_users";
		// Template Settings
		$data['content_title'] = 'User Management';
		$data['left_sidebar'] = 'admin_links';
		$data['sidebar_modifier'] = 'Hide Right';
		$data['left_sidebar_title'] = 'Administration';

		// Load the manage users view for the admin section
		$this->load->view('template', $data);

	}

	public function manage_classes() {
		// Check if the user is logged in and has permission to view page
		if ( ! $this->user->is_logged()  ) { redirect('welcome/login'); }
		if ( ! $this->user->is_administrator() || $this->user->is_lecturer() ) { redirect('welcome/login'); }

		// Load the classes model 
		$this->load->model('classes');

		// A FORM HAS BEEN SUBBMITTED! DO SOMETHING!!!
		if ( $this->input->post() ) {
			
			// Check if the user is adding a class (A tutor_id has been posted)
			if ( $this->input->post('tutor_id') != '' ) {
				// Get the post data
				$data = $this->input->post();
				// Load the add class function from the user model
				if ( $this->classes->add_class($data) ) {
					$this->session->set_flashdata('notices', 'Class added successfully.' );
				} else {
					$this->session->set_flashdata('errors', 'Error: Cannot create class. Please try again.' );
				}
				redirect('admin/manage_classes');
			}

		}

		// Check if the user wants to delete a class
		if ( $this->uri->segment(3) === 'delete' ) {
			if ( $this->uri->segment(4) ) {
				$this->classes->remove_class( $this->uri->segment(4) );
				$this->session->set_flashdata('notices', 'Class removed successfully.' );
			} else {
				$this->session->set_flashdata('errors', 'Error: Cannot delete class.' );
			}
			redirect('admin/manage_classes');
		}

		// Get a list of tutors
		$data['tutors'] = $this->user->get_user_data( null, 'tutor' );
		// Get a list of classes
		$data['classes'] = $this->classes->get_class_data();

		// Page title to send to view
		$data['page_title'] = "Administration";
		// Page content 
		$data['main_content'] = "admin/manage_classes";
		// Template Settings
		$data['content_title'] = 'Class Management';
		$data['left_sidebar'] = 'admin_links';
		$data['sidebar_modifier'] = 'Hide Right';
		$data['left_sidebar_title'] = 'Administration';
		// Load the settings view for the admin section
		$this->load->view('template', $data);
	}

	public function settings() {
		// Check if the user is logged in and has permission to view page
		if ( ! $this->user->is_logged()  ) { redirect('welcome/login'); }
		if ( ! $this->user->is_administrator() ) { redirect('welcome/login'); }

		$this->load->model('settings');

		if ( $this->input->post() ) {
			$settings = $this->input->post();
			$this->settings->update_settings($settings);
			$this->session->set_flashdata('notices', 'Settings updated successfully.' );
			redirect('admin/settings');
		}

		// Page title to send to view
		$data['page_title'] = "Administration";
		// Page content 
		$data['main_content'] = "admin/settings";
		// Current settings
		$data['settings'] = $this->settings->get_settings();

		// Template Settings
		$data['content_title'] = 'Settings';
		$data['left_sidebar'] = 'admin_links';
		$data['sidebar_modifier'] = 'Hide Right';
		$data['left_sidebar_title'] = 'Administration';

		// Load the settings view for the admin section
		$this->load->view('template', $data);
	}

	public function export_data() {
		// Check if the user is logged in and has permission to view page
		if ( ! $this->user->is_logged()  ) { redirect('welcome/login'); }
		if ( $this->user->is_student() ) { redirect('welcome/login'); }

		$this->load->model('classes');
		$this->load->model('groups');

		if ( $this->input->post() ) {
			
			$data = $this->input->post();
			$class_id = $data['class_id'];

			if ($data['export'] == 'groups') {
				
				// Gat an array for all students and their groups
				$csv_data = $this->groups->get_groups_and_students($class_id);
				// Set the headers for the csv file
				$headers = array('Group Name', 'Student First Name', 'Student Last Name');
				// Create the file
				$this->_create_csv($csv_data, $headers);

				// Prevent the HTMl from being included in the csv file
				return;

			} else if ($data['export'] == 'results') {
				
				// Gat an array for all students and their groups
				$csv_data = $this->user->get_student_marks($class_id);
				// Set the headers for the csv file
				$headers = array('Student ID', 'First Name', 'Last Name', 'Result', '%');
				// Create the file
				$this->_create_csv($csv_data, $headers);

				// Prevent the HTMl from being included in the csv file
				return;

			}

		}

		$data['classes'] = $this->classes->get_class_data();

		// Page title to send to view
		$data['page_title'] = "Administration";
		// Page content 
		$data['main_content'] = "admin/export_data";

		// Template Settings
		$data['content_title'] = 'Export Data';
		$data['left_sidebar'] = 'admin_links';
		$data['sidebar_modifier'] = 'Hide Right';
		$data['left_sidebar_title'] = 'Administration';

		// Load the settings view for the admin section
		$this->load->view('template', $data);

	}

	public function enter_feedback() {

		// Check if the user is logged in and has permission to view page
		if ( ! $this->user->is_logged()  ) { redirect('welcome/login'); }
		if ( $this->user->is_student() ) { redirect('welcome/login'); }

		$this->load->model('classes');
		$this->load->model('groups');
		$this->load->model('assessments');

		if ($this->input->post('grade')) {

			// Check no feedback submitted yet
			$assessment_id = $this->input->post('assessment_id');
			$user_id = $this->input->post('user_id');
			if ( $this->assessments->check_feedback_exists($user_id, $assessment_id) ) {
				$this->session->set_flashdata('errors', 'You have already entered feedback for this user.' );
				redirect('admin/enter_feedback');
			} 

			if ( $this->assessments->add_feedback( $this->input->post() ) ) {
				$this->session->set_flashdata('notices', 'Feedback entered.' );
			} else {
				$this->session->set_flashdata('errors', 'A database error occured. Please try again.' );
			}
			redirect('admin/enter_feedback'); 
		}

		$data['assessments'] = $this->assessments->get_all_assessment_items();
		$data['students'] = $this->user->get_user_data(null, 'student');

		$data['student_feedback'] = $this->assessments->get_all_feedback();

		// Page title to send to view
		$data['page_title'] = "Administration";
		// Page content 
		$data['main_content'] = "admin/enter_feedback";

		// Template Settings
		$data['content_title'] = 'Enter Assessment Grades & Reviews';
		$data['left_sidebar'] = 'admin_links';
		$data['sidebar_modifier'] = 'Hide Right';
		$data['left_sidebar_title'] = 'Administration';

		// Load the settings view for the admin section
		$this->load->view('template', $data);

	}


	public function delete_feedback() {
		// Check if the user is logged in and has permission to view page
		if ( ! $this->user->is_logged()  ) { redirect('welcome/login'); }
		if ( $this->user->is_student() ) { redirect('welcome/login'); }

		$this->load->model('assessments');

		if ( $this->uri->segment(3) ) {

			if ( $this->assessments->delete_feedback( $this->uri->segment(3) ) ) {
				$this->session->set_flashdata('notices', 'Feedback deleted.' );
			} else {
				$this->session->set_flashdata('errors', 'An error occured. Please try again.' );
			}
			redirect('admin/enter_feedback'); 
		}
	}

	public function peer_reviews() {
		// Check if the user is logged in and has permission to view page
		if ( ! $this->user->is_logged()  ) { redirect('welcome/login'); }
		if ( $this->user->is_student() ) { redirect('welcome/login'); }

		$this->load->model('classes');
		$this->load->model('groups');
		$this->load->model('assessments');
		$this->load->model('settings');

		// Get some data like a badass
		$data['assessments'] = $this->assessments->get_all_assessment_items();
		$data['students'] = $this->user->get_user_data(null, 'student');
		$data['week_offset'] = $this->settings->get_setting('first_week');
		$data['week_limit'] = $this->settings->get_setting('weeks');
        $data['groups'] = $this->groups->get_group_list();

		if ( $this->input->post() ) {
			$data['peer_reviews'] = $this->assessments->get_peer_reviews(
					$this->input->post('user_id'),
					$this->input->post('assessment_id'),
					$this->input->post('week_no'),
					$this->input->post('group_id')
				);
		} else {
			$data['peer_reviews'] = $this->assessments->get_peer_reviews();
		}

		// Page title to send to view
		$data['page_title'] = "Administration";
		// Page content 
		$data['main_content'] = "admin/peer_reviews";

		// Template Settings
		$data['content_title'] = 'View Peer Reviews';
		$data['left_sidebar'] = 'admin_links';
		$data['sidebar_modifier'] = 'Hide Right';
		$data['left_sidebar_title'] = 'Administration';

		// Load the settings view for the admin section
		$this->load->view('template', $data);
	}


	/**
	 * Converts an array into a csv file.
	 * @param arr $data Array for data to export
	 * @param arr $headers Headers of the CSV file
	 */
	private function _create_csv($data, $headers) {
		$attachment = true;

		// Create a random filename
		$filename = $this->_file_name() . '.csv';

		if($attachment) {
            // send response headers to the browser
            header( 'Content-Type: text/csv' );
            header( 'Content-Disposition: attachment;filename='.$filename);
            $f = fopen('php://output', 'w');
        } else {
            $f = fopen($filename, 'w');
        }
        
        if($headers) {
            fputcsv($f, $headers);
        }
        
        foreach ($data as $key => $value) {
        	fputcsv($f, $value);
        }
        
        fclose($f);
    }


	private function _file_name() {
		$length = 10;
		$alfa = "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
		$token = "";
		for($i = 0; $i < $length; $i ++) {
			$token .= $alfa[rand(0, strlen($alfa) - 1)];
		}    
		return $token;
	}

}

/* End of file admin.php */
/* Location: ./application/controllers/admin.php */